﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace common
{
    public class Log
    {
        private string _filename;

        public string Filename
        {
            get { return _filename; }
            set { _filename = value; }
        }

        public Log()
        {
            _filename = "log/request.log";
        }
        public Log(string filename)
        {
            this._filename = filename;
        }

        public static StringBuilder sb = new StringBuilder();
        public static int count = 10;//最短记录条数，10条。
        public static int clearTime = 60000;//最短记录时间1分钟。

        public static DateTime lastClear = DateTime.Now;//最后清除的时间。
        public static int currentIndesx = 0;

        public void Append(string text)
        {
            currentIndesx++;
            sb.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + text + "\r\n");

            TimeSpan ts = DateTime.Now - lastClear;
            if (currentIndesx >= count || ts.TotalMilliseconds >= clearTime)
            {
                Write(sb.ToString());
                sb.Remove(0, sb.Length);

                lastClear = DateTime.Now;
                currentIndesx = 0;
            }
        }

        public bool Write(string text)
        {
            FileStream fs = new FileStream(Filename, FileMode.Append);
            byte[] b = Encoding.GetEncoding("gb2312").GetBytes(text);
            fs.Write(b, 0, b.Length);
            fs.Flush();
            fs.Close();
            return true;
        }
    }
}
